define(function () {
    'use strict';

    function ctrl($scope,$timeout,$stateParams,$ionicPopup,$ionicLoading,$ionicHistory,CommonService,DictionaryService,InfoService,WebService,$filter) {

        var par = $scope.param = {};

        $scope.$on('$ionicView.beforeEnter', function() {
            par.allotNo = $stateParams['allotNo'];     //申请编号 证券理财 银行理财
            par.prodCode = $stateParams['prodCode'];     //产品代码 集中交易
            par.prodSource = $stateParams['prodSource'];     //基金类型 0:银行理财   1:证券理财  2：集中交易

            init();
        });

        function init(){
            par.isSuccess = false;
            par.prodName = "";  //产品名称

            $scope.sell = {};
            $scope.sell.placeholder = "请输入卖出份额";
            $scope.pay = {};  //支付银行信息
            $scope.short_fund = {};  //短债产品

            if(CommonService.isStrEmpty(par.prodCode) || CommonService.isStrEmpty(par.prodSource)){
                var alertPopup = CommonService.showConfig({message : "未选择任何产品"});
                $timeout(function() {
                    alertPopup.close();
                    $ionicHistory.goBack();
                }, 3000);
            }
            //份额查询
            queryFund();
            //产品信息查询
            queryProductInfo();
        }

        $scope.sellClick = function (){
            if(checkNext1()){
                $scope.sell2 = {}; //第二步
                if(!$scope.sell2Popup) {
                    $scope.sell2Popup = $ionicPopup.show({
                        template:
                            '<div class="kDlgCell"><p>卖出品种：</p><div>'+par.prodName+'</div></div>'+
                            '<div class="kDlgCell"><p>卖出份额：</p><div><em style="color:#eb6c35" >'+ $filter('defNumber')($scope.sell.amount,2) +'</em>份</div></div>',
                        title: "确认卖出信息",
                        scope: $scope,
                        cssClass: "kDialog",
                        buttons: [
                            { text: "取消" },
                            { text: "<b>确定</b>",
                                type: "button-positive",
                                onTap: function(e) {
                                    e.preventDefault();
                                    redeem();
                                }
                            }
                        ]
                    });
                    $scope.sell2Popup.then(function(res) {
                        $scope.sell2Popup = null;
                    })
                }
            }
        };

        function queryFund(){
            WebService.getShares(par.prodSource, par.allotNo, par.prodCode).then(
                function (data) {
                    if (data && data.length == 1) {
                        $scope.holdFund = data[0];
                        //产品名称获取
                        if(par.prodSource=="1"){
                            par.prodName = $scope.holdFund.prod_name;
                        }else{
                            par.prodName =  $scope.holdFund.fund_name;
                        }
                        //证券理财显示赎回银行卡 银行理财 集中交易 保证金账户
                        if(par.prodSource == "1") {
                            getBankByTransAccount();
                        }else {
                            $scope.pay.bank_name = "您的保证金账户";
                        }
                        //持仓显示 短债产品控制为26文件解析的可赎回份额 证券理财 集中交易
                        shortEnableAmount();
                    }else {
                        CommonService.showAlert({message:"持仓信息查询失败",onUnblock:function (){
                            $timeout(function(){
                                $ionicHistory.goBack();
                            },3000);
                        }});
                    }
                }
            );
        }

        function shortEnableAmount(){
            InfoService.getShortTermFund(par.prodCode,$scope.holdFund.trans_account).then(function(short_term_fund){
                var enable_amount = "";
                if(short_term_fund && short_term_fund.length != 0){
                    $scope.short_fund = short_term_fund[0];
                    enable_amount = parseFloat($scope.short_fund.availablevol);
                    //减去委托里的委托数量
                    WebService.getOrders(par.prodSource, par.prodCode, $scope.holdFund.trans_account).then(
                        function (data){
                            if(data && data.length > 0){
                                if(par.prodSource=="1"){
                                    for (var i = 0; i < data.length; i++) {
                                        var record = data[i];
                                        enable_amount = enable_amount - parseFloat(record.entrust_amount);
                                    }
                                }
                                if(par.prodSource=="2"){
                                    for (var i = 0; i < data.length; i++) {
                                        var record = data[i];
                                        enable_amount = enable_amount - parseFloat(record.shares);
                                    }
                                }
                            }

                            $scope.sell.placeholder = "≤" + CommonService.controlNum(enable_amount,2);
                            $scope.sell.allShare = Number(CommonService.controlNum(enable_amount,2));
                        }
                    );
                }else{

                    enable_amount = $scope.holdFund.enable_amount;
                    $scope.sell.placeholder = "≤" + CommonService.controlNum(enable_amount,2);
                    $scope.sell.allShare = Number(CommonService.controlNum(enable_amount,2));
                }
            });
        }

        function getBankByTransAccount(){
            WebService.getBankByTransAccount($scope.holdFund.trans_account).then(
                function (data) {
                    if(CommonService.isStrEmpty(data.bank_no)) {
                        $scope.pay.bank_name = "您的保证金账户";
                    } else {
                        $scope.pay.bank_no = data.bank_no;
                        $scope.pay.bank_name = data.bank_name;
                        $scope.pay.pay_account = data.pay_account;
                    }
                }
            );
        }

        function queryProductInfo(){
            WebService.queryIFSProdInfo(par.prodCode, par.prodSource).then(
                function (data){
                    if(data && data.length == 1){
                        $scope.ifsProdInfo = data[0];
                    }else{
                        CommonService.showAlert({message:"未查到产品信息"});
                    }
                }
            );
        }

        function redeem(){
            $ionicLoading.show();
            var amount = $scope.sell.amount;
            var redeemPromise = null;
            //银行理财暂无赎回业务
            if(par.prodSource=="1"){
                redeemPromise = WebService.redeemDjProduct(par.prodCode, $scope.holdFund.prodta_no, amount, par.allotNo,
                    $scope.holdFund.prod_name, $scope.pay.bank_name, $scope.pay.pay_account);
            }else if(par.prodSource=="2"){
                redeemPromise = WebService.redeemUfProduct(par.prodCode, $scope.holdFund.fund_company, amount,
                    $scope.holdFund.fund_name);
            }
           redeemPromise.then(
               function (data){
                   if(data){
                        $scope.sell2Popup.close();
                        var date = data.redeem_complete_date;
                        if(!CommonService.isStrEmpty($scope.pay.pay_account)){
                            date = data.redeem_success_date;
                        }
                        var redeem_show_date = "--";
                        if(!CommonService.isStrEmpty(date) && date.length==8){
                            var redeemShowDate = new Date(date.substr(0,4),parseFloat(date.substr(4,2))-1,date.substr(6,2));
                            redeem_show_date = new XDate(redeemShowDate).toString("MM-dd") + " " + weeks[redeemShowDate.getDay()];
                        }
                        $scope.sell.redeem_show_date = redeem_show_date;
                        par.isSuccess = true;
                        $ionicLoading.hide();
                   }
               },
               function (result){
                    if("XCM-300001" == result.error_no) {//显示通知
                        CommonService.showNotice(result.error_info);
                    }else if(result.error_no == "XCM-100002") {
                        CommonService.showAlert({message:result.error_info});
                    } else {
                        CommonService.showConfig({message:result.error_info});
                    }
               }
            );
        }

        function checkNext1(){
            if($scope.holdFund == null || $scope.ifsProdInfo == null){
                CommonService.showAlert({message:"未查到卖出基金信息"});
                return false;
            }
            var amount = $scope.sell.amount;
            if(CommonService.isStrEmpty(amount) || isNaN(amount)){
                CommonService.showAlert({message:"请输入有效数据！"});
                return false;
            }
            if (!CommonService.checkRegex("^[0-9]+(.[0-9]{1,2})?$",amount)) {
                CommonService.showAlert({message:"卖出份额只能精确到小数点后1到2位！"});
                return false;
            }
            amount = Number(amount);
            if(amount <= 0) {
                CommonService.showAlert({message:"卖出份额应大于0"});
                $("#amount").val("");
                return false;
            }
            var allShare = $scope.sell.allShare;
            if(amount > allShare) {
                CommonService.showAlert({message:"卖出份额应小于等于" + allShare});
                $scope.sell.amount = 0;
                return false;
            }
            if(amount == allShare){
                //全部卖出时，不再限制
                return true;
            }
            if(amount < $scope.ifsProdInfo.redeem_limitshare) {
                CommonService.showAlert({message:"卖出份额应大于等于" +  $scope.ifsProdInfo.redeem_limitshare + "或选择全部卖出"});
                $scope.sell.amount = 0;
                return false;
            }
            //最低持有份额
            var hold_minshare = 0;
            if(null != $scope.short_fund){
                hold_minshare = 1000;
            }
            if(!CommonService.isStrEmpty( $scope.ifsProdInfo.hold_minshare)){
                hold_minshare = Number( $scope.ifsProdInfo.hold_minshare);
            }
            if(allShare!=amount && (allShare - amount) < hold_minshare){
                if(allShare > 1000){
                    CommonService.showAlert({message:"卖出后的当期剩余份额不可低于"+hold_minshare+"份，请选择全部卖出或者减少卖出份额。"});
                }else{
                    CommonService.showAlert({message:"卖出后的当期剩余份额不可低于"+hold_minshare+"份，请选择全部卖出。"});
                }
                return false;
            }
            return true;
        }

        var weeks = DictionaryService.getWeeks();
    }

    ctrl.$inject = ['$scope','$timeout','$stateParams','$ionicPopup','$ionicLoading','$ionicHistory','CommonService','DictionaryService','InfoService','WebService','$filter'];
    return ctrl;
});
